<template>
  <view class="page">
    <view class="nav">
      <text class="title">PDF去水印</text>
    </view>

    <view class="upload-card" @tap="selectPdf">
      <t-icon name="file-pdf" size="40" />
      <text class="upload-tip">点击上传PDF文件</text>
      <text class="upload-sub">或拖拽文件至此处</text>
      <text v-if="selectedFileName" class="file-name"
        >已选择：{{ selectedFileName }}</text
      >
    </view>

    <view class="option-card">
      <view class="opt-row" @tap="toggleImageWM">
        <text class="opt-title">选择图片水印</text>
        <t-icon :name="imageWM ? 'chevron-up' : 'chevron-down'" size="22" />
      </view>
      <view class="divider" />
      <view class="opt-row" @tap="toggleTextWM">
        <text class="opt-title">选择文字水印</text>
        <t-icon :name="textWM ? 'chevron-up' : 'chevron-down'" size="22" />
      </view>
    </view>

    <view class="actions">
      <t-button
        theme="warning"
        variant="outline"
        block
        style="margin-bottom: 16rpx"
        @tap="toggleMode"
      >
        {{ aggressive ? "强力模式" : "安全模式" }}
      </t-button>
      <t-button theme="warning" block :disabled="processing" @tap="startRemove">
        {{ processing ? "处理中..." : "开始去水印" }}
      </t-button>
      <t-button
        v-if="resultFileID"
        theme="warning"
        block
        variant="outline"
        style="margin-top: 16rpx"
        @tap="downloadResult"
      >
        下载到手机
      </t-button>
    </view>
  </view>
</template>

<script>
import {
  isCloudReady,
  uploadPdfToCloud,
  removePdfWatermark,
} from "../../services";
import {
  downloadAndSaveCloudFile,
  addDownloadRecord,
} from "../../services/files";
export default {
  data() {
    return {
      selectedFilePath: "",
      selectedFileName: "",
      imageWM: false,
      textWM: false,
      processing: false,
      resultFileID: "",
      aggressive: false,
    };
  },
  methods: {
    /**
     * 返回上一页
     */
    goBack() {
      uni.navigateBack();
    },
    /**
     * 选择PDF文件（聊天/本地）
     */
    selectPdf() {
      uni.chooseMessageFile({
        count: 1,
        type: "file",
        extension: ["pdf"],
        success: (res) => {
          const f = res.tempFiles && res.tempFiles[0];
          if (f) {
            this.selectedFilePath = f.path;
            this.selectedFileName = f.name || `未命名-${Date.now()}.pdf`;
          }
        },
      });
    },
    /**
     * 切换图片水印选项（占位交互，不影响处理逻辑）
     */
    toggleImageWM() {
      this.imageWM = !this.imageWM;
    },
    /**
     * 切换文字水印选项（占位交互，不影响处理逻辑）
     */
    toggleTextWM() {
      this.textWM = !this.textWM;
    },
    /**
     * 开始去水印流程：上传到云端 -> 云函数处理 -> 返回新 fileID
     */
    async startRemove() {
      if (!this.selectedFilePath) {
        uni.showToast({ title: "请先选择PDF文件", icon: "none" });
        return;
      }
      if (!isCloudReady()) {
        uni.showToast({ title: "云开发未初始化", icon: "none" });
        return;
      }
      this.processing = true;
      try {
        const fileID = await uploadPdfToCloud(
          this.selectedFilePath,
          this.selectedFileName
        );
        const newId = await removePdfWatermark(fileID, {
          mode: this.aggressive ? "aggressive" : "safe",
        });
        this.resultFileID = newId;
        const history = uni.getStorageSync("wm_history") || [];
        history.unshift({
          fileID: newId,
          src: fileID,
          time: Date.now(),
          name: this.selectedFileName,
        });
        uni.setStorageSync("wm_history", history);
        uni.showToast({ title: "去水印完成", icon: "success" });
      } catch (e) {
        uni.showToast({ title: "处理失败", icon: "none" });
      } finally {
        this.processing = false;
      }
    },
    /** 切换清理模式（安全/强力） */
    toggleMode() {
      this.aggressive = !this.aggressive;
    },
    /**
     * 下载处理结果到本地并加入“我的下载”
     */
    async downloadResult() {
      try {
        const cleanName =
          this.selectedFileName.replace(/\.pdf$/i, "") + "-clean.pdf";
        const localPath = await downloadAndSaveCloudFile(
          this.resultFileID,
          cleanName
        );
        addDownloadRecord({
          name: cleanName,
          size: "-",
          time: Date.now(),
          fileID: this.resultFileID,
          savedPath: localPath,
        });
        wx.openDocument({
          filePath: localPath,
          fileType: "pdf",
          showMenu: true,
        });
      } catch (_) {
        uni.showToast({ title: "下载失败", icon: "none" });
      }
    },
  },
};
</script>

<style>
.page {
  padding: 24rpx;
}
.nav {
  display: flex;
  align-items: center;
  gap: 12rpx;
}
.title {
  font-size: 32rpx;
  font-weight: 600;
}
.upload-card {
  margin-top: 24rpx;
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx 24rpx;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 12rpx;
}
.upload-tip {
  font-size: 30rpx;
  font-weight: 600;
}
.upload-sub {
  color: #8c8c8c;
  font-size: 24rpx;
}
.file-name {
  color: #8c8c8c;
  font-size: 24rpx;
}
.option-card {
  margin-top: 24rpx;
  background: #fff;
  border-radius: 20rpx;
  padding: 16rpx 24rpx;
}
.opt-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
}
.opt-title {
  font-size: 28rpx;
}
.divider {
  height: 1px;
  background: #f0f0f0;
}
.actions {
  margin-top: 24rpx;
}
</style>
